package com.timepies.button;

import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.timepies.ElencoPieActivity;
import com.timepies.DettaglioPieActivity;
import com.timepies.R;
import com.timepies.domain.Timepie;
import com.timepies.domain.TimepieAdapterDatabase;

public class PieListView {

	public static ListView addTo(final ElencoPieActivity activity) {
		Cursor cursor = activity.getDb().query();
		ListView list = (ListView) activity.findViewById(R.id.pie_main_list);
		list.setAdapter(new TimepieAdapterDatabase(activity, cursor, 0));
		list.setOnItemClickListener(getListener(activity));

		TextView istruzioni = (TextView) activity.findViewById(R.id.istruzioni);
		if (list == null || list.getCount() == 0)
			istruzioni.setVisibility(View.VISIBLE);
		else
			istruzioni.setVisibility(View.GONE);

		return list;
	}

	private static OnItemClickListener getListener(
			final ElencoPieActivity activity) {

		return new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Log.d(this.getClass().getSimpleName(), "position:" + position
						+ " id:" + id);

				String data = ((TextView) v.findViewById(R.id.txt_date))
						.getText().toString();

				String testo = ((TextView) v.findViewById(R.id.txt_testo))
						.getText().toString();

				String oggetto = ((TextView) v.findViewById(R.id.txt_oggetto))
						.getText().toString();

				Intent i = new Intent(activity, DettaglioPieActivity.class);
				i.putExtra("pieObj", new Timepie(id, data, oggetto, testo));
				activity.startActivity(i);
				activity.finish();
				Log.d(this.getClass().getSimpleName(), "position:" + position
						+ " id:" + id + " SENDED!");

			}
		};
	}
}
